<?php

namespace App\Core\Utils\Wechat;

use App\Core\Utils\TwHelper\CommFunction;
use App\Core\Utils\Wechat\WechatConfig;

/**
 * 微信相关操作接口(部门)
 */
class WechatDepartmentService
{
    private $accessToken;

    public function __construct()
    {
        $this->accessToken = WechatConfig::getAccessToken();
    }

    /**
     * 创建部门
     * 参考:http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E9%83%A8%E9%97%A8#.E5.88.9B.E5.BB.BA.E9.83.A8.E9.97.A8
     */
    public function addWechatDepartment($params = array())
    {
        $url = sprintf('%s?%s', WechatConfig::WECHAT_OPTION_DEPARTMENT_ADD, $this->accessToken);
        $result = CommFunction::postCurl($url, json_encode($params));
        if ($result ['errcode'] == 0) {
            return $result ['id'];
        } else {
            return false;
        }
    }

    /**
     * 更新部门
     * 参考:http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E9%83%A8%E9%97%A8#.E6.9B.B4.E6.96.B0.E9.83.A8.E9.97.A8
     */
    public function updateWechatDepartment($params = array())
    {
        $url = sprintf('%s?%s', WechatConfig::WECHAT_OPTION_DEPARTMENT_UPDATE, $this->accessToken);
        $result = CommFunction::postCurl($url, json_encode($params));
        if ($result ['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除部门
     * 参考:http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E9%83%A8%E9%97%A8#.E5.88.A0.E9.99.A4.E9.83.A8.E9.97.A8
     */
    public function delWechatDepartment($departmentId)
    {
        $params['access_token'] = $this->accessToken;
        $params['id'] = $departmentId;
        $url = sprintf('%s?%s', WechatConfig::WECHAT_OPTION_DEPARTMENT_DEl, http_build_query($params));
        $result = CommFunction::getCurl($url);
        if ($result ['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取部门列表
     * 参考：http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E9%83%A8%E9%97%A8#.E5.88.A0.E9.99.A4.E9.83.A8.E9.97.A8
     */
    public function getDepartment($departmentId)
    {
        $params['access_token'] = $this->accessToken;
        $params['id'] = $departmentId;
        $url = sprintf('%s?%s', WechatConfig::WECHAT_OPTION_DEPARTMENT_GET, http_build_query($params));
        $result = CommFunction::getCurl($url);
        if ($result ['errcode'] == 0) {
            return $result;
        } else {
            return false;
        }
    }

}